'use strict'

const Service = require('egg').Service

class wxUserService extends Service {

    async login(param){
        const {app,ctx,service} = this;
        const {phone,password,type} = param;

        let user = await ctx.model.FdUser.findOne({where:{phone:phone,type:type}});

        if(app.lodash.isEmpty(user)){
            ctx.throw(402,'该手机号未注册！');
        }

        if(user.deleted == '1'){
            ctx.throw(402,'该手机号未注册！');
        }

        if(user.forbidden == '1'){
            ctx.throw(402,'该用户已被禁用！');
        }

        if(user.password != await service.utils.md5(password)){
            ctx.throw(402,'密码错误！');
        }

        return user;
    }

    async register(param){
        const {app,ctx,service} = this;

        //引入uuid生成器
        var uuid = require('node-uuid');

        //开启事务
        let t = await ctx.model.transaction();
        try {
            //定义新增的对象
            param.id = uuid.v1();
            param.deleted = '0';
            param.type = '3';
            param.username = param.phone;
            param.password = await service.utils.md5(param.password);
            param.forbidden = '0';
            //调用sequelize新增对象 findOrCreate 将返回一个数组[对象，新增成功与否的布尔] 如果新增对象已存在，则返回该对象和false 否则返回新增对象和true
            let rs = await ctx.model.FdUser.findOrCreate({where:{phone:param.phone,type:'3',deleted:'0'},defaults:param,transaction:t});

            //提交事务
            t.commit();

            //返回新增结果
            return rs[1];

        }catch (e) {
            //若出错 回滚
            t.rollback();
            //抛出出错信息
            ctx.throw(500,e.message)
        }
    }

    async forgot(param){
        const {app,ctx,service} = this;
        switch (param.type) {
            case 'customer':
                param.type = '3'; break;
            case 'runner':
                param.type = '2'; break;
            case 'center':
                param.type = '1'; break;
        }
        const {phone,password,type} = param;

        let user = await ctx.model.FdUser.findOne({where:{phone:phone,type:type}});

        if(app.lodash.isEmpty(user)){
            ctx.throw(402,'该手机号未与任何账号绑定');
        }

        user.password = await service.utils.md5(password);

        await user.save();

        app.sessionStore.destroy('code_'+phone);

        return user;

    }
}

module.exports = wxUserService
